package com.testmall.interceptor;

import com.testmall.entity.common.TokenProperties;
import com.testmall.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @Description:
 * @Author: littleDesire
 * @Date: 2022-06-23 8:39
 * @Version: 1.0
 */

public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    TokenProperties tokenProperties;

    @Autowired
    TokenUtil tokenUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!tokenProperties.getEnable()) {
            return true;
        }
        // 默认请求可以访问
        boolean result = true;
        String info = null;
        String token = request.getHeader("x-token");
        if (null == token) {
            // 没有token则直接返回数据false
            info = error("您无权访问");
            // 无权访问
            result = false;
        }else {
            // 进行token验证
            Map<String, Object> rs = tokenUtil.verifyToken(token);
            int code = Integer.parseInt(rs.get("code").toString());
            if ( code != 200){
                info = error(rs.get("msg").toString());
                return false;
            }
        }
        if (!result){
            // 无权访问 响应客户端请求
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(info);
            return false;
        }
        return true;
    }

    String error(String msg) {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append("\"code\":0,");
        sb.append("\"msg\":");
        sb.append("\"");
        sb.append(msg);
        sb.append("\"");
        sb.append("}");
        return sb.toString();
    }
}
